package pjkanri.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.sql.DataSource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import pjkanri.entity.Account;

public class AccountDAO {

	public Account findByNameAndPassword(String name, String password)
			throws DAOException {

		Account account = null;
		String sql = "SELECT * FROM account WHERE name = ? AND password = ?";

		DataSource ds = DataSourceFactory.getDataSource();

		try (Connection conn = ds.getConnection();
				PreparedStatement pstmt = conn.prepareStatement(sql)) {

			pstmt.setString(1, name);
			pstmt.setString(2, password);

			try (ResultSet rs = pstmt.executeQuery()) {

				if (rs.next()) {
					account = new Account();
					account.setId(rs.getInt("id"));
					account.setName(rs.getString("name"));
					account.setEmail(rs.getString("email"));
					account.setPassword(rs.getString("password"));
				}
			}

		} catch (SQLException e) {
			throw new DAOException(e);
		}

		return account;
	}

	/**
	 * @param email
	 * @param password
	 * @return
	 * @throws DAOException
	 */
	public Account findByEmailAndPassword_1(String email, String password)
			throws DAOException {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();

		Account account = (Account) session.createCriteria(Account.class)
				.add(Restrictions.eq("email", email))
				.add(Restrictions.eq("password", password)).uniqueResult();

		return account;
	}

	/**
	 * @param account
	 * @return
	 */
	public void insert(Account account) throws DAOException {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			account.setId(getMaxId()+1);
			session.save(account);
	}
	
	/**
	 * @param account
	 * @return
	 */
	public void update(Account acc) throws DAOException {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			
			// トランザクション開始とTransactionオブジェクトの取得
//			Transaction tx = session.beginTransaction();
			
			Account account = (Account) session.get(Account.class, acc.getId());
			
			account.setName(acc.getName());
			account.setPassword(acc.getPassword());
			account.setEmail(acc.getEmail());
			
//			tx.commit();
	}
	
	/**
	 * @return
	 * @throws DAOException
	 */
	private Integer getMaxId() throws DAOException{
		
		Integer maxId = 0;
		String sql = "SELECT Max(id) as max FROM ACCOUNT ";

		DataSource ds = DataSourceFactory.getDataSource();

		try (Connection conn = ds.getConnection();
				Statement pstmt = conn.createStatement()) {

			try (ResultSet rs = pstmt.executeQuery(sql)) {

				if (rs.next()) {
					if (rs.getString("max") == null ) return 0;
					maxId = Integer.parseInt(rs.getString("max"));
				}
			}

		} catch (SQLException e) {
			throw new DAOException(e);
		}
		return maxId;
	}
	
	/**
	 * Hibernateの使用
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Account> getAccountList()
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		Criteria criteria = session.createCriteria(Account.class);
		criteria.addOrder(Order.asc("id"));
		
		List<Account> listAccount = criteria.list();
//		for (Account account : listAccount) {
//			System.out.println(account);
//		}
		
		return listAccount;
	}
}
